package com.zt.model.util;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

public class DBUtil {
    private DBUtil(){};
    private static SqlSessionFactory factory =null;

    /**
     * 功能：获取SqlSessionFactory
     * @return factory
     */
    public static SqlSessionFactory getFactory(){
        if (Objects.isNull(factory)){
            try {
                InputStream stream = Resources.getResourceAsStream("mybatis/mybatis-config.xml");
                factory = new SqlSessionFactoryBuilder().build(stream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return factory;
    }

    /**
     * 功能：关闭sqlSession
     * @param sqlSession
     */
    public static void close(SqlSession sqlSession){
        if (Objects.nonNull(sqlSession))
            sqlSession.close();
    }
}
